package com.jt.admin.service.impl;

import com.jt.admin.common.exception.CustomException;
import com.jt.admin.common.exception.user.UserPasswordNotMatchException;
import com.jt.admin.common.utils.R;
import com.jt.admin.common.utils.ServletUtils;
import com.jt.admin.domain.entity.SysUserEntity;
import com.jt.admin.domain.model.LoginBody;
import com.jt.admin.domain.model.LoginUser;
import com.jt.admin.service.SysLoginService;
import com.jt.admin.service.SysMenuService;
import com.jt.admin.service.SysRoleService;
import com.jt.admin.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.Authenticator;
import java.util.Set;

/**
 * 系统登录
 */
@Service
public class SysLoginServiceImpl implements SysLoginService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    SysRoleService sysRoleService;


    @Override
    public String login(LoginBody loginBody) {
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword())
            );

        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        assert authentication != null;
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }

    /**
     * 获取用户信息
     * @return
     */
    @Override
    public R getUserInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUserEntity user = loginUser.getUser();
        // 菜单权限
        Set<String> permissions = sysMenuService.getMenuPerMissionByUserId(user.getUserId());
        // 角色
        Set<String> roles = sysRoleService.getRoleByUserId(user.getUserId());

        return R.success()
                .put("user",user)
                .put("roles",roles)
                .put("permissions",permissions);
    }
}
